from google.appengine.ext import db
from google.appengine.ext import blobstore

"""
Represents a directory that an Asset can be 
stored in.
"""
class Directory(db.Model):
    
    """
    Name of the directory.
    """
    name = db.StringProperty(multiline = False)

    """
    Name of the directory's parent directory.
    """
    parent_directory = db.SelfReferenceProperty()

    """
    When the directory was created.
    """
    created = db.DateTimeProperty(auto_now_add = True)

    """
    Who created the directory.
    """
    created_by = db.StringProperty(multiline = False)

    """
    Static method used to get the root directory.
    """
    @staticmethod
    def get_root():
        results = db.GqlQuery("SELECT * FROM Directory WHERE name = :n", n = "")
        if results.count() == 0:
            # If no results returned, create a new root.
            d = Directory(name = "")
            d.put()
            return d
        else:
            # Return the first result.
            return results[0]
    
    """
    Return's a directory's path.
    """
    def path(self):
        current = self
        path = ""
        while current is not None:
            path = current.name + "/" + path
            current = current.parent_directory
        return path

    """
    Gets a list of the sub-directories of this directory
    """
    def dir(self):
        # Return a list of directory objects whos parent is this.
        results = db.GqlQuery("SELECT * FROM Directory WHERE parent_directory = :k", k = self)

        dirs = [Directory.get_root()]
        if self.parent_directory is not None:
            dirs.append(self.parent_directory)
        dirs.append(self)

        for r in results:
            dirs.append(r)
        return dirs

"""
Represents a file stored in the Blobstore.
"""
class Asset(db.Model):
    
    """
    Key of the Asset in the Blobstore.
    """
    asset_key = blobstore.BlobReferenceProperty()

    """
    Directory the Asset is stored in.
    """
    directory = db.ReferenceProperty(Directory)

    """
    When the Asset was created."
    """
    created = db.DateTimeProperty(auto_now_add = True)

    """
    Who the Asset was created by.
    """
    created_by = db.StringProperty(multiline = False)

